package com.skd.mall.seckill.service.Impl;

import com.alibaba.fastjson.JSON;
import com.skd.common.constant.OrderConstant;
import com.skd.common.constant.SeckillConstant;
import com.skd.common.utils.R;
import com.skd.common.vo.MemberVO;
import com.skd.mall.seckill.dto.SeckillOrderDto;
import com.skd.mall.seckill.dto.SeckillSkuRedisDto;
import com.skd.mall.seckill.fegin.CouponServiceFegin;
import com.skd.mall.seckill.fegin.ProductFeginService;
import com.skd.mall.seckill.interceptor.AuthInterceptor;
import com.skd.mall.seckill.service.SeckillService;
import com.skd.mall.seckill.vo.SeckillSessionEntity;
import com.skd.mall.seckill.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponServiceFegin couponServiceFegin;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeginService productFeginService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 查询当前时间内的秒杀商品
     * @return
     */
    @Override
    public List<SeckillSkuRedisDto>  getCurrentSeckillSkus() {
        //1确定当前时间是属于那个秒杀活动
        Long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SeckillConstant.SESSION_CHACE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SeckillConstant.SESSION_CHACE_PREFIX, "");
            String[] s = replace.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            if (time > start && time < end){
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SKU_CHACE_PREFIX);
                List<String> list = ops.multiGet(range);
                if(list != null&& list.size()>0){
                    List<SeckillSkuRedisDto> collect = list.stream().map(item -> {
                        SeckillSkuRedisDto dto = JSON.parseObject(item, SeckillSkuRedisDto.class);
                        return dto;
                    }).collect(Collectors.toList());
                    return collect;
                }
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisDto getSeckillSessionBySkuId(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SKU_CHACE_PREFIX);
        Set<String> keys = ops.keys();
        String regx = "\\d_"+skuId;
        for (String key : keys) {
            boolean matches = Pattern.matches(regx, key);
            if(matches){
                String json = ops.get(key);
                SeckillSkuRedisDto dto = JSON.parseObject(json, SeckillSkuRedisDto.class);
                return dto;
            }
        }
        return null;
    }

    /**
     * 实现秒杀逻辑
     * @param killId
     * @param code
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String code, Integer num) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SKU_CHACE_PREFIX);
        String json = ops.get(killId);
        if(StringUtils.isNotBlank(json)){
            SeckillSkuRedisDto dto = JSON.parseObject(json, SeckillSkuRedisDto.class);
            //1检验时效性
            Long startTime = dto.getStartTime();
            Long endTime = dto.getEndTime();
            Long now = new Date().getTime();
            if (now > startTime && now<endTime){
                //在活动时间范围内
                //校验商品是否合法
                String randCode = dto.getRandCode();
                Long skuId = dto.getSkuId();
                String redisKilled = dto.getPromotionSessionId()+"_"+skuId;
                if(randCode.equals(code) && killId.equals(redisKilled)){
                    //随机码检验合格
                    //受否满足幂等性
                    if(num <= dto.getSeckillLimit().intValue()){
                        //只要抢购成功就会在redis中储存一条消息userId + sessionID + skuId
                        MemberVO memberVO = (MemberVO)AuthInterceptor.threadLocal.get();
                        Long id = memberVO.getId();
                        String redisKey = id + "_" + redisKilled;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), (endTime - now), TimeUnit.MICROSECONDS);
                        if(aBoolean){
                            // 表示数据插入成功 是第一次操作
                            RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE+randCode);
                            try {
                                boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                if(b){
                                    // 表示秒杀成功
                                    // 创建订单编号
                                    // 创建一个 DateTimeFormatter 对象，定义不使用分隔符的格式
                                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                                    // 获取当前日期和时间
                                    LocalDateTime now1 = LocalDateTime.now();
                                    // 使用自定义的格式化器格式化日期和时间
                                    String formattedDateTime = now1.format(formatter);
                                    Random random = new Random();
                                    // 生成一个四位长度的随机数字，最高位不为0
                                    int fourDigitNumber = 1000 + random.nextInt(9000);
                                    if (fourDigitNumber < 1000) {
                                        fourDigitNumber += 1000;
                                    }
                                    String orderSN = fourDigitNumber+formattedDateTime;
                                    // 继续完成快速下订单操作  --> RocketMQ
                                    SeckillOrderDto orderDto = new SeckillOrderDto() ;
                                    orderDto.setOrderSN(orderSN);
                                    orderDto.setSkuId(skuId);
                                    orderDto.setSeckillPrice(dto.getSeckillPrice());
                                    orderDto.setMemberId(id);
                                    orderDto.setNum(num);
                                    orderDto.setPromotionSessionId(dto.getPromotionSessionId());
                                    // 通过RocketMQ 发送异步消息
                                    rocketMQTemplate.sendOneWay(OrderConstant.ROCKETMQ_SECKILL_ORDER_TOPIC
                                            ,JSON.toJSONString(orderDto));
                                    return orderSN;
                                }
                            } catch (InterruptedException e) {
                                return null;
                            }
                        }
                    }
                }
            }
        }

        return null;
    }

    /**
     * 上架秒杀商品
     */
    @Override
    public void uploadSeckillSku3Days() {
        // 1. 通过OpenFegin 远程调用Coupon服务中接口来获取未来三天的秒杀活动的商品
        R r = couponServiceFegin.getSeckillSkuRelationService();
        String json = (String) r.get("data");
        List<SeckillSessionEntity> seckillSessionEntities = JSON.parseArray(json, SeckillSessionEntity.class);
        // 2. 上架商品  Redis数据保存
        // 缓存商品
        //  2.1 缓存每日秒杀的SKU基本信息
        saveSessionInfos(seckillSessionEntities);
        // 2.2  缓存每日秒杀的商品信息
        saveSessionSkuInfos(seckillSessionEntities);

    }

    /**
     * 保存每日活动的信息到Redis中
     * @param seckillSessionEntities
     */
    private void saveSessionSkuInfos(List<SeckillSessionEntity> seckillSessionEntities) {
        for (SeckillSessionEntity seckillSessionEntity : seckillSessionEntities) {
            // 循环缓存每一个活动  key： start_endTime
            long start = seckillSessionEntity.getStartTime().getTime();
            long end = seckillSessionEntity.getEndTime().getTime();
            // 生成Key
            String key = SeckillConstant.SESSION_CHACE_PREFIX+start+"_"+end;
            Boolean flag = redisTemplate.hasKey(key);
            if(!flag){// 表示这个秒杀活动在Redis中不存在，也就是还没有上架，那么需要保存
                // 需要存储到Redis中的这个秒杀活动涉及到的相关的商品信息的SKUID
                List<String> collect = seckillSessionEntity.getRelationEntities().stream().map(item -> {
                    // 秒杀活动存储的 VALUE是 sessionId_SkuId
                    return item.getPromotionSessionId()+"_"+item.getSkuId().toString();
                }).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,collect);
            }
        }
    }


    /**
     * 存储活动对应的 SKU信息
     * @param seckillSessionEntities
     */
    private void saveSessionInfos(List<SeckillSessionEntity> seckillSessionEntities) {
        seckillSessionEntities.stream().forEach(session ->{
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SeckillConstant.SKU_CHACE_PREFIX);
            session.getRelationEntities().stream().forEach(item->{
                String skuKey = item.getPromotionSessionId()+"_"+item.getSkuId();
                Boolean flag = hashOps.hasKey(skuKey);
                if(!flag){
                    SeckillSkuRedisDto dto = new SeckillSkuRedisDto();
                    // 1.获取SKU的基本信息
                    R info = productFeginService.info(item.getSkuId());
                    if(info.getCode() == 0){
                        // 表示查询成功
                        String json = (String) info.get("skuInfoJson");
                        dto.setSkuInfoVo(JSON.parseObject(json,SkuInfoVo.class));
                    }
                    // 2.获取SKU的秒杀信息
                    BeanUtils.copyProperties(item,dto);
                    // 3.设置当前商品的秒杀时间
                    dto.setStartTime(session.getStartTime().getTime());
                    dto.setEndTime(session.getEndTime().getTime());
                    // 4. 随机码
                    String token = UUID.randomUUID().toString().replace("-","");
                    dto.setRandCode(token);
                    //绑定对应的活动编号
                    dto.setPromotionSessionId(item.getPromotionSessionId());
                    // 分布式信号量的处理  限流的目的
                    RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + token);
                    // 把秒杀活动的商品数量作为分布式信号量的信号量
                    semaphore.trySetPermits(item.getSeckillCount().intValue());
                    hashOps.put(skuKey,JSON.toJSONString(dto));
                }
            });
        });
    }

}
